//
//  DemandAndServiceSearchTabVC.m
//  BusinessMarket
//
//  Created by Michael Li on 2018/12/25.
//  Copyright © 2018年 Michael Li. All rights reserved.
//

#import "DemandAndServiceSearchTabVC.h"
#import "ServiceCell.h"
#import "DemandCell.h"
#import "HomeModel.h"
#import "ServiceModel.h"
#import "HomeSearchHeadView.h"
#import "DemandTheHallContentVC.h"
#import "ServiceContentTabVC.h"
@interface DemandAndServiceSearchTabVC ()<HomeSearchHeadViewDelegate,DZNEmptyDataSetSource, DZNEmptyDataSetDelegate,DemandCellDelegate>
@property(nonatomic,strong) NSMutableArray *dataMuta;
@property(nonatomic,strong) AFHTTPSessionManager *manager;
@property(nonatomic,strong) NSString *urlString;
@property(nonatomic,strong) NSDictionary *dict;
@property(nonatomic,assign) NSInteger pageNum;
@property(nonatomic,assign) NSInteger pageSize;
@property(nonatomic,strong) HomeSearchHeadView *searchView;
@property(nonatomic,strong) NSString *text;
@property(nonatomic,strong) MJRefreshAutoNormalFooter *footer;
@end
static NSString *identifierDemand = @"DemandCell";
static NSString *identifierService = @"ServiceCell";
static NSString *identifierCondition = @"SearchConditionCell";
@implementation DemandAndServiceSearchTabVC
-(NSMutableArray *)dataMuta
{
    if (!_dataMuta) {
        _dataMuta = [NSMutableArray array];
    }
    return _dataMuta;
}
- (void)viewDidAppear:(BOOL)animated
{
    [self.searchView.tf becomeFirstResponder];
}
- (void)viewWillAppear:(BOOL)animated
{
    [self.navigationController.navigationBar setBackgroundImage:[ImageColorHelper createImageWithColor:[UIColor colorWithRed:248/255.0 green:248/255.0 blue:248/255.0 alpha:1]] forBarMetrics:UIBarMetricsDefault];
}
- (void)viewWillDisappear:(BOOL)animated
{
    [self.searchView.tf resignFirstResponder];
    [self.navigationController.navigationBar setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsDefault];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.manager = [AFHTTPSessionManager manager];
    self.pageNum = 1;
    self.pageSize = 10;
    self.tableView.tableFooterView = [[UIView alloc]initWithFrame:CGRectZero];
    self.searchView = [[HomeSearchHeadView alloc]initWithFrame:CGRectMake(0, 0, kVWidth*0.8,self.navigationController.navigationBar.frame.size.height-8)];
    __weak typeof (self)weakSelf = self;
    self.searchView.returnValueSearcBlock = ^(NSInteger selected, NSString * _Nonnull text) {
        weakSelf.text = text;
        
    };
    self.searchView.delegate = self;
    self.navigationItem.titleView = self.searchView;
    self.searchView.returnValueSearcBlock = ^(NSInteger selected, NSString * _Nonnull text) {
        weakSelf.text = text;
        weakSelf.dataMuta = nil;
        
        [weakSelf reloadInternetData];
        [weakSelf.searchView.tf resignFirstResponder];
    };
//    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(refresh)];
//    [header isRefreshing];
    
     [self.tableView registerNib:[UINib nibWithNibName:@"DemandCell" bundle:nil] forCellReuseIdentifier:identifierDemand];
    [self.tableView registerNib:[UINib nibWithNibName:@"ServiceCell" bundle:nil] forCellReuseIdentifier:identifierService];
    [self.tableView registerNib:[UINib nibWithNibName:@"SearchConditionCell" bundle:nil] forCellReuseIdentifier:identifierCondition];
    
}

//-(void)refresh
//{
//    self.dataMuta = nil;
//    //    self.believeArray = nil;
//    self.pageNum = 1;
//    //    self.pageSize = 10;
//    [self reloadInternetData];
//
//}
-(void)reloadMore
{
    self.pageNum ++;
    
    [self reloadInternetData];
    
}
#pragma mark-代理:即时搜索
- (void)homeSearchHeadView:(id)homeSearchHeadView withTFChange:(UITextField *)tfChange
{
    self.dataMuta = nil;
    self.text = tfChange.text;
    [self reloadInternetData];
}
-(void)reloadInternetData
{
    [WSProgressHUD setProgressHUDIndicatorStyle:WSProgressHUDIndicatorBigGray];
    [WSProgressHUD show];
    if (self.searchIndex == 1) {
        self.urlString = [NSString stringWithFormat:@"%@/demand/selectTranslateDemand",kUrl];
        self.dict = @{
                      @"pageNum":[NumberSwitchString numberSwitchString:self.pageNum],
                      @"pageSize":[NumberSwitchString numberSwitchString:self.pageSize],
                      @"ass":self.text,
                      @"assub":@"",
                      @"uid":[UserDefaultsHelper readUid],
                      @"token":[UserDefaultsHelper readToken]
                      };
    }else {
        self.urlString = [NSString stringWithFormat:@"%@/association/indexSearch",kUrl];
        self.dict = @{
                      @"page":[NumberSwitchString numberSwitchString:self.pageNum],
                      @"rows":[NumberSwitchString numberSwitchString:self.pageSize],
                      @"param":self.text
                      };
    }
    XLog(@"self.dict:%@",self.dict);
    [self.manager POST:self.urlString parameters:self.dict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSArray *temp = [responseObject objectForKey:@"date"];
//        XLog(@"responseObject:%@",responseObject);
        if (temp.count) {
            if (self.searchIndex == 1) {
                for (NSDictionary *dict in temp) {
                    HomeModel *model =[HomeModel mj_objectWithKeyValues:dict];
                    [self.dataMuta addObject:model];
                }
            }else {
                for (NSDictionary *dict in temp) {
                    ServiceModel *model = [ServiceModel mj_objectWithKeyValues:dict];
                    [self.dataMuta addObject:model];
                }
            }
            
            [self.tableView.mj_footer endRefreshing];
        }else {
            self.tableView.emptyDataSetSource = self;
            self.tableView.emptyDataSetDelegate = self;
        }
        XLog(@"self.dataMuta.count:%ld",self.dataMuta.count);
        XLog(@"self.dataMuta:%@",self.dataMuta);
        if (self.dataMuta.count) {
            self.footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(reloadMore)];
            self.tableView.mj_footer = self.footer;
            if (!temp.count) {
                self.tableView.mj_footer.state = MJRefreshStateNoMoreData;
            }
        }else {
            [self.footer removeFromSuperview];
        }
        [self.tableView reloadData];
        [self.tableView.mj_header endRefreshing];
        [WSProgressHUD dismiss];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataMuta.count;
}

- (nonnull UITableViewCell *)tableView:(nonnull UITableView *)tableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
    [tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    if (self.searchIndex == 1) {
        DemandCell *cell = [tableView dequeueReusableCellWithIdentifier:identifierDemand forIndexPath:indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.delegate = self;
        cell.indexPath = indexPath;
        HomeModel *model = self.dataMuta[indexPath.row];
        cell.homeModel = model;
        return cell;
    }else {
        ServiceCell *cell = [tableView dequeueReusableCellWithIdentifier:identifierService forIndexPath:indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        ServiceModel *model = self.dataMuta[indexPath.row];
        cell.serviceModel = model;
        
        return cell;
    }
    
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.searchIndex == 1) {
        HomeModel *model = self.dataMuta[indexPath.row];
        DemandTheHallContentVC *vc = [[DemandTheHallContentVC alloc]init];
        vc.homeModel = model;
        vc.returnValueBlock = ^(NSInteger selected) {
            model.collectStatus = selected;
            [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
        };
        [self.navigationController pushViewController:vc animated:YES];
    }else {
        ServiceModel *model = self.dataMuta[indexPath.row];
        ServiceContentTabVC *vc = [[ServiceContentTabVC alloc]init];
        vc.model = model;
        [self.navigationController pushViewController:vc animated:YES];
    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{

    return 144;
}
#pragma mark-代理:显示联系人
-(void)demandCell:(DemandCell *)demandCell withClickBtn:(UIButton *)clickBtn withIndexPath:(NSIndexPath *)indexPath withHomeModel:(HomeModel *)homeModel
{
    
    if ([[UserDefaultsHelper readAutoLogIn] isEqualToString:@"NO"]||[UserDefaultsHelper readAutoLogIn].length == 0) {
        LogInOrOutVC *logVC = [[LogInOrOutVC alloc]init];
        MainNavC *mianNav = [[MainNavC alloc]initWithRootViewController:logVC];
        
        [self presentViewController:mianNav animated:YES completion:^{
            [UserDefaultsHelper saveUid:@"" value:nil];
            [UserDefaultsHelper saveToken:@"" value:nil];
            [UserDefaultsHelper saveAutoLogIn:@"" value:@"NO"];
            
        }];
    }else {
        self.dict = @{
                      @"userId":[UserDefaultsHelper readUid],
                      @"token":[UserDefaultsHelper readToken]
                      };
        XLog(@"self.dict:%@",self.dict);
        self.urlString = [NSString stringWithFormat:@"%@/user/checkToken",kUrl];
        [self.manager POST:self.urlString parameters:self.dict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSInteger status = [[responseObject objectForKey:@"status"] integerValue];
            if (status == 200) {
                HomeModel *model = self.dataMuta[indexPath.row];
                model.show = clickBtn.selected;
                [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
            }else {
                [UIAlertViewWarningAccount showWarningAccount];
                [LogOutAccount presentOutAccount];
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
        }];
        
    }
}
#pragma mark-代理:收藏

- (void)demandCell:(DemandCell *)demandCell withCollectBtn:(UIButton *)clickBtn withIndexPath:(NSIndexPath *)indexPath withHomeModel:(HomeModel *)homeModel
{
    XLog(@"clickBtn:%d",clickBtn.selected);
    if ([[UserDefaultsHelper readAutoLogIn] isEqualToString:@"NO"]) {
        LogInOrOutVC *logVC = [[LogInOrOutVC alloc]init];
        MainNavC *mianNav = [[MainNavC alloc]initWithRootViewController:logVC];
        [self presentViewController:mianNav animated:YES completion:^{
            [UserDefaultsHelper saveUid:@"" value:nil];
            [UserDefaultsHelper saveToken:@"" value:nil];
            [UserDefaultsHelper saveAutoLogIn:@"" value:@"NO"];
            
        }];
    }else{
        
        self.dict = @{
                      @"userId":[UserDefaultsHelper readUid],
                      @"token":[UserDefaultsHelper readToken]
                      };
        self.urlString = [NSString stringWithFormat:@"%@/user/checkToken",kUrl];
        [self.manager POST:self.urlString parameters:self.dict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            XLog(@"responseObject:%@",responseObject);
            //            NSString *message = [responseObject objectForKey:@"message"];
            NSInteger status = [[responseObject objectForKey:@"status"] integerValue];
            if (status == 200) {
                clickBtn.selected = !clickBtn.selected;
                if (clickBtn.selected) {
                    homeModel.collectStatus = 1;
                }else {
                    homeModel.collectStatus = 0;
                }
                NSString *ids = [NSString stringWithFormat:@"%ld",homeModel.id];
                XLog(@"self.homeModel.id:%ld",homeModel.id);
                NSString *collect = [NSString stringWithFormat:@"%d",clickBtn.selected];
                self.dict = @{
                              @"uid":[UserDefaultsHelper readUid],
                              @"id":ids,
                              @"type":@"1",
                              @"status":collect,
                              @"token":[UserDefaultsHelper readToken]
                              };
                XLog(@"self.dict:%@",self.dict);
                [CustomeManager POSTWithURLIndex:34 parameters:self.dict success:^(NSDictionary *dict) {
                } failure:^(NSError *error) {
                    
                }];
                
            }else {
                [UIAlertViewWarningAccount showWarningAccount];
                [LogOutAccount presentOutAccount];
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
        }];
    }
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    self.tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
}
- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView {
    UIImage *image = [UIImage imageNamed:@"empty"];
    return image;
}
- (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView {
    NSString *title = [NSBundle bundleLocalizedStringForKey:@"noData"];
    NSDictionary *attributes = @{
                                 NSFontAttributeName:[UIFont boldSystemFontOfSize:14],
                                 NSForegroundColorAttributeName:kLabel102Color
                                 };
    return [[NSAttributedString alloc] initWithString:title attributes:attributes];
}
@end
